// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database();
const $ = db.command.aggregate

// 创建集合云函数入口函数
exports.main = async (event, context) => {
    try {
        let {
            conditions
        } = event.data

        // 获取当前日期
        const now = new Date();

        let startOfDay, endOfDay

        if (conditions.currentDate == 1) {
            // 今日
            startOfDay = new Date(now);
            startOfDay.setHours(0, 0, 0, 0);
            endOfDay = new Date(now);
            endOfDay.setHours(23, 59, 59, 999);
        } else if (conditions.currentDate == 2) {
            // 本周
            const dayOfWeek = now.getDay(); // 0-6, 0代表周日
            startOfDay = new Date(now);
            startOfDay.setHours(0, 0, 0, 0);
            startOfDay.setDate(now.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1))

            endOfDay = new Date(startOfDay);
            endOfDay.setHours(23, 59, 59, 999);
            endOfDay.setDate(startOfDay.getDate() + 6)
        } else if (conditions.currentDate == 3) {
            // 本月
            startOfDay = new Date(now.getFullYear(), now.getMonth(), 1);
            endOfDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
            endOfDay.setHours(23, 59, 59, 999);
        }

        let query = db.collection('orderList')

        // 查询商品抵扣金额、优惠券抵扣金额、实付金额 占比
        const discountResult = await query.aggregate().match({
                _openid: conditions._openid,
                orderStatus: {
                    $not: {
                        $in: [1, 5], // 查询状态除了待付款和售后以为的订单
                    }
                },
                createTime: {
                    $gte: startOfDay,
                    $lte: endOfDay
                },
                payTime: {
                    $gte: startOfDay,
                    $lte: endOfDay
                }
            })
            .group({
                _id: null,
                goodsDiscountNum: $.sum('$goodsDiscountNum'), // 商品抵扣金额
                couponDiscount: $.sum('$couponDiscount'), // 优惠券抵扣金额
                payAmount: $.sum('$payAmount'), // 实付金额
            })
            .end()

        let discountData = []
        if (discountResult.list.length > 0) {
            discountData = discountResult.list.map(item => {
                return {
                    goodsDiscountNum: item.goodsDiscountNum,
                    couponDiscount: item.couponDiscount,
                    payAmount: item.payAmount,
                }
            })
        }

        return {
            code: 200,
            msg: "操作成功",
            data: discountData[0]
        }
    } catch (err) {
        return {
            code: 500,
            message: err.message
        }
    }
}